<?php
/**
 * This controller is uses to proccess department
 *
 * @author	huytbt
 * @date	2012-04-21
 * @version	1.0
 */
class DepartmentController extends HController
{
	/**
	 * This action is uses to display list department of textbook
	 */
	public function actionIndex($university_id = null)
	{
		// Get current user
		Yii::import('application.modules.user.models.User');
		$user = User::model()->findByPk(Yii::app()->user->id);
		
		$university = null;
		if ($university_id == null) {
			// Get the first university of user
			Yii::import('application.modules.textbooks.models.TextbookUniversity');
			$universities = $user->universities;
			
			if ($universities)
				$university = $user->universities[0]->university;
			else
				$this->redirect(array('/textbooks/profile/universities'));
		} else {
			// Get university
			Yii::import('application.modules.textbooks.models.TextbookUniversity');
			$university = TextbookUniversity::model()->findByPk($university_id);
		}
		
		// If does not exists university then redirect to page select university
		if (!$university)
			$this->redirect(array('/textbooks/selectUniversity'));
		
		// Select all departments of current university
		Yii::import('application.modules.textbooks.models.TextbookDepartment');
		$departments = TextbookDepartment::model()->getDepartmentsByUniversity($university->id);
		
		// Register assets
		$baseScriptUrl = Yii::app()->assetManager->publish(dirname(__FILE__) . '/../assets');
		Yii::app()->clientScript->registerScriptFile($baseScriptUrl . '/js/jquery.h.textbooks.department.js');
		Yii::app()->clientScript->registerScriptFile($baseScriptUrl . '/js/jquery.h.textbooks.book.js');
		
		$this->render('index', array(
			'university' => $university,
			'departments' => $departments,
		));
	}
	
	/**
	 * This action is used to add department
	 *
	 * @param university_id ID of university
	 */
	public function actionAdd($university_id)
	{
		if (Yii::app()->request->isAjaxRequest && isset($_POST['TextbookDepartment'])) {
			// Check university is exists or not?
			Yii::import('application.modules.textbooks.models.TextbookUniversity');
			$university = TextbookUniversity::model()->findByPk($university_id);
			if (!$university)
				$this->renderJSON(self::ERROR, 'The university does not exists.');
			
			Yii::import('application.modules.textbooks.models.TextbookDepartment');
			$model = new TextbookDepartment;
			$model->name = trim($_POST['TextbookDepartment']['name']);
			$model->university_id = $university_id;
			
			// validate input
			if ($model->save()) {
				$this->renderJSON(self::SUCCESS, 'Add new department successful.');
			} else {
				$this->renderJSON(self::ERROR, 'Validate failed', $model->getErrors());
			}
		}
		
		$this->renderJSON(self::ERROR, 'Your request is invalid.');
	}
}
